package xyz.jcat.web.security;

import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetailsService;
import xyz.jcat.common.util.CodeUtils;
import xyz.jcat.common.web.RespCodeMsg;
import xyz.jcat.security.UserRoleAuthenticationToken;

import java.util.Objects;

public class AccountAuthenticationProvider implements AuthenticationProvider {

    private UserDetailsService userDetailsService;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String username = (String) authentication.getPrincipal();
        String password = (String) authentication.getCredentials();

        UserDetailsImpl user = (UserDetailsImpl) userDetailsService.loadUserByUsername(username);
        if(Objects.isNull(user) || !CodeUtils.checkPwd(password, user.getPassword())) {
            throw new BadCredentialsException(RespCodeMsg.ACCOUNT_OR_PWD_ERROR.getMsg());
        }
        return new UserRoleAuthenticationToken(user.getId(), user.getRoles());
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return true;
    }

    public AccountAuthenticationProvider(UserDetailsService userDetailsService) {
        this.userDetailsService = userDetailsService;
    }
}
